package chances.epg.data.taglib;

import java.util.List;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.data.taglib.page.PageInfo;
import chances.epg.entity.content.AlbumItem;
import chances.epg.navigator.context.AccessContextUtils;


/**
 * 专栏内容列表. 支持分页查询.
 * 
 * @author Elysium
 * 
 */
public class AlbumItemTag extends QueryListTag {
	private static final Logger logger = EpgLogFactory.getSystemLogger();

	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 1242068837815231172L;

	private String code;// Album code
	private int size;

	@Override
	public int doEndTag() throws JspException {
		if (StringUtils.isNotBlank(this.getPageName())) {
			this.queryItemByPage(this.code);
		} else {
			this.queryItemBySize(this.code);
		}

		return super.doEndTag();
	}

	/**
	 * 分页查询.
	 */
	private void queryItemByPage(String albumCode) {
		try {
			PageInfo pageInfo = this.createPageInfo(size);
			List<AlbumItem> result = this.getContentService().getAlbumItems(
					albumCode, this.start, pageInfo.getPageBean());
			this.setPageInfo(pageInfo);
			this.setAlbumItem(result);
		} catch (Throwable ex) {
			logger.error("AlbumItemTag error", ex);
		}
	}

	/**
	 * 查询指定数量的条目.
	 */
	private void queryItemBySize(String albumCode) {
		try {
			List<AlbumItem> result = this.getContentService().getAlbumItems(
					albumCode, this.start, this.size);
			this.setAlbumItem(result);
		} catch (Throwable ex) {
			logger.error("AlbumItemTag error", ex);
		}
	}

	private void setAlbumItem(List<AlbumItem> result) {
		for (AlbumItem albumItem : result) {
			albumItem
					.setUrl(navigateUrlFactory.generateURL(
							AccessContextUtils.getAccessContext(pageContext),
							albumItem));
		}

		this.setCollectionResult(result);
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}
}
